package cn.mrcode.wxsdk.core.dialogue.common.distributed;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * zk客户端工具类
 * @author zhuqiang
 * @version V1.0
 * @date 2015/9/23 15:32
 */
@Deprecated
public class ZkClientUtil {
    private static Logger log = LoggerFactory.getLogger(ZkClientUtil.class);
    /**
     * 创建ZK连接
     *
     * @param connectString  ZK服务器地址列表
     * @param sessionTimeout Session超时时间 毫秒
     * @param watcher 监视者
     */
    public static ZooKeeper createConnection(String connectString, int sessionTimeout,Watcher watcher) {
        ZooKeeper result = null;
        try {
            result = new ZooKeeper(connectString, sessionTimeout, watcher);
        } catch (IOException e) {
            e.printStackTrace();
            String errMsg = "创建ZooKeeper 客户端失败：" + e.getMessage();
            log.error(errMsg);
            throw new RuntimeException("zk 初始化失败：" + errMsg);
        }
        return result;
    }

    /**
     * 关闭ZK连接
     */
    public static void releaseConnection(ZooKeeper zk) {
        if (zk != null) {
            try {
                zk.close();
            } catch (InterruptedException e) {
                // ignore
                e.printStackTrace();
            }
        }
    }

    /**
     *
     * @param zk
     * @param path 节点path
     * @param data 初始数据内容
     * @param createMode
     * @return
     */
    public static String createPath(ZooKeeper zk,String path, String data, CreateMode createMode) {
        String result = null;
        try {
            result = zk.create(path, //
                    data.getBytes("utf-8"), //
                    ZooDefs.Ids.OPEN_ACL_UNSAFE, //
                    createMode);
//            log.info("节点:" + result + " 创建成功");
        } catch (KeeperException e) {
            String errMsg = "节点创建失败，发生KeeperException：" + e.getMessage();
            log.error(errMsg);
            throw new RuntimeException(errMsg);
        } catch (InterruptedException e) {
            String errMsg = "节点创建失败，发生InterruptedException:" + e.getMessage();
            log.error(errMsg);
            throw new RuntimeException(errMsg);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 读取指定节点数据内容
     *
     * @param path 节点path
     *
     * @return
     */
    public static String readData(ZooKeeper zk,String path) {
        try {
            byte[] data = zk.getData(path, false, null);
//            log.i("获取数据成功，path：" + path);
            try {
                return new String(data,"utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        } catch (KeeperException e) {
            log.error("读取数据失败，发生KeeperException，path: " + path + ":" + e.getMessage());
            e.printStackTrace();
            return "";
        } catch (InterruptedException e) {
            log.error("读取数据失败，InterruptedException，path: " + path + ":" + e.getMessage());
            e.printStackTrace();
            return "";
        }
        return null;
    }

    /**
     * 判断是否存在该目录，不监视改变
     * @param zk
     * @param path
     * @return 返回true 已经存在
     */
    public static boolean exists(ZooKeeper zk,String path){
        try {
            Stat exists = zk.exists(path, false);
            return exists == null?false:true;
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 更新指定节点数据内容
     * @param path 节点path
     * @param data  数据内容
     * @return
     */
    public static boolean writeData(ZooKeeper zk,String path, String data) {
        try {
            Stat stat = zk.setData(path, data.getBytes(), -1);
//            log.i("更新数据成功，path：" + path +  " : stat= " + JSON.toJSONString(stat));
        } catch ( KeeperException e ) {
            log.error( "更新数据失败，发生KeeperException，path: " + path  );
            e.printStackTrace();
        } catch ( InterruptedException e ) {
            log.error( "更新数据失败，发生 InterruptedException，path: " + path  );
            e.printStackTrace();
        }
        return false;
    }
}
